import { defineStore } from 'pinia'
import router, { routers } from '@/router'
import { getMenuList } from '@/api/menu'
import { RouterView } from 'vue-router'
import Layout from '@/layout/AppLayout.vue'
const modules = import.meta.glob('@/views/**/**.vue')
export const useSystem = defineStore('systemStore', {
  state: () => ({
    isCollapse: false, // 菜单是否展开面包屑列表
    menuList: [] as any[]// 菜单列表
  }),
  getters: {
    get: (state) => {
      return {
        isCollapse: state.isCollapse,
        menuList: state.menuList
      }
    }
  },
  actions: {
    // 是否展开
    setIsCollapse (payload: boolean): void {
      this.isCollapse = payload
    },
    async getMenuList () {
      // eslint-disable-next-line array-callback-return
      routers.forEach((item) => {
        if (item.children !== undefined) {
          this.menuList.push(item.children[0])
        }
      })
      const result = await getMenuList()
      const menus = result.map((item: any): any => {
        const ret: any = {
          path: '',
          component: Layout,
          children: []
        }
        ret.children[0] = item
        ret.children = formatChildren(ret.children)
        this.menuList.push(ret.children[0])
        router.addRoute(ret)
        return ret
      })
      return menus
    }
  }
})
// 格式化子级路由
function formatChildren (children: any[]): any[] {
  const ret = children.map((item: any): any => {
    const obj: any = {
      path: item.path,
      name: item.path,
      component: null,
      meta: {
        title: item.menu_name,
        icon: item.icon,
        menu_type: item.menu_type
      },
      children: []
    }
    if (item.menu_type === 'M') { // 目录
      obj.component = RouterView
    }
    if (item.menu_type === 'C') { // 菜单
      obj.component = modules[`/src/views/${item.component}.vue`]
    }
    // 参数存在拼接参数
    if (item.query !== undefined && item.query !== '' && item.query !== null) {
      obj.path = item.path + item.query
    }
    // 有子级路由
    if (item.children !== undefined && item.children.length > 0) {
      obj.children = formatChildren(item.children)
    } else {
      delete obj.children
    }
    return obj
  })
  return ret
}
